package com.ay.weixin.mail.domain;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.lizar.exception.LifecycleException;
import org.lizar.ioc.Lifecycle;
import org.lizar.ioc.module.Module;
import org.lizar.util.VelocityHelper;

import freemarker.template.TemplateException;

public class MailBox extends Module implements Lifecycle  {
	private Logger log = Logger.getLogger(MailBox.class);
	private static ConcurrentLinkedQueue<Email> queue=new java.util.concurrent.ConcurrentLinkedQueue<Email>();
	
	private boolean start=true;
	
	public void sendMail(Email email) {
		queue.add(email);
	}
	
	
	public void init_property() throws Exception {
		
	}

	

	private void _send(Email email) throws AddressException,MessagingException, IOException, TemplateException {
		Properties props = new Properties();
		props.put("mail.smtp.socketFactory.fallback", "false");
		props.put("mail.smtp.starttls.enable","true");
		props.put("mail.smtp.socketFactory.port", email.getMailbox_mail_server_port());
		props.put("mail.debug", "true"); 
		props.put("mail.smtp.host", email.getMailbox_mail_server());
		props.put("mail.smtp.port",email.getMailbox_mail_server_port());
		props.put("mail.smtp.auth", "true");
		Session session = Session.getDefaultInstance(props, email.getAuthenticator());
		MimeMessage message = new MimeMessage(session);

		List<InternetAddress> reply_addresses = email.getReplyto_addresses();
		if (reply_addresses != null && !reply_addresses.isEmpty()){
			InternetAddress[] addresses = new InternetAddress[reply_addresses.size()];
			reply_addresses.toArray(addresses);
			message.setReplyTo(addresses);
		}
		message.setSubject(email.getMailSubject());
		String emailContent=VelocityHelper.read_msg(email.getTemplatePath(), email.getContext());
		message.setContent(emailContent, "text/html;charset=utf-8");
		message.setSentDate(new Date());
		message.setFrom(new InternetAddress(email.getMailbox_user_name(), email.getPersonalName()));
		for (InternetAddress addr : email.getReplyto_addresses()) {
			message.addRecipient(Message.RecipientType.BCC, addr);
		}
		Transport.send(message);
	}

	public static void main(String[] args){
		  VelocityEngine ve = new VelocityEngine();
		  ve.init();
		  // 输出流
		  StringWriter writer = new StringWriter();
		  VelocityContext context=new VelocityContext();
		  context.put("value", "11");
		  // 转换输出
		  ve.evaluate(context, writer, "", "$value"); // 关键方法
		   writer.toString();
		   System.out.println(writer);
	}


	@Override
	public void init_component() throws Exception {
		Thread t=new Thread(new Runnable() {
			public void run() {
				while(start){
					Email email=queue.poll();
					if(email!=null){
						try {
							_send(email);
						} catch (Exception e) {
							log.error("邮件发送失败",e);
						}
					}
					try {
						Thread.sleep(60*1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		t.start();
	}


	@Override
	public void born() throws LifecycleException, Exception {
		start=true;
		
	}


	@Override
	public void die() throws LifecycleException {
		start=false;
		
	}

}
